package cn.qyd.aqs;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 邱运铎
 * 在使用ReentrantLock的时候在锁必须在try语句块之前，并且保证加锁之前不能出现异常
 * 因为在try语句块总出现异常，会在直接执行finally中释放锁语句，而此时因为还没有获得锁会导致无法释放锁出现异常
 * @date 2024-03-19 13:38
 */
public class ReentrantLockDemo01 {
    //ReentrantLock 默认构造方法是创建非公平锁
//    private static final ReentrantLock lock = new ReentrantLock();
    //在构造ReentrantLock的时候传入参数，true表示公平锁，false和空表示非公平锁
    private static final ReentrantLock lock = new ReentrantLock(true);
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                lock.lock();
                try {
                    count++;
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                lock.lock();
                try {
                    count++;
                } finally {
                    lock.unlock();
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println(count);


    }
}
